<!--

/*
* Copyright (C) 2005-2013 University of Sydney
*
* Licensed under the GNU License, Version 3.0 (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
*
* http://www.gnu.org/licenses/gpl-3.0.txt
*
* Unless required by applicable law or agreed to in writing, software distributed under the License
* is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
* or implied. See the License for the specific language governing permissions and limitations under
* the License.
*/

/**
* discussionTab.html
* record edit form threaded discussion area
* Added Ian Johnson 25/3/2010 - broken out from the text/annotation tab
*
* @author      Tom Murtagh
* @author      Kim Jackson
* @author      Ian Johnson   <ian.johnson@sydney.edu.au>
* @author      Stephen White   <stephen.white@sydney.edu.au>
* @author      Artem Osmakov   <artem.osmakov@sydney.edu.au>
* @copyright   (C) 2005-2013 University of Sydney
* @link        http://Sydney.edu.au/Heurist
* @version     3.1.0
* @license     http://www.gnu.org/licenses/gpl-3.0.txt GNU License 3.0
* @package     Heurist academic knowledge management system
* @subpackage  !!!subpackagename for file such as Administration, Search, Edit, Application, Library
*/

-->


<html>

    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
        <link rel=stylesheet href="../../../common/css/global.css">
        <link rel=stylesheet href="../../../common/css/edit.css">

        <script>
            function onshow() {}
            top.HAPI.importSymbols(top, this);
        </script>

    </head>
    <body class="editTab" onload="onshow()">

        <form></form>

        <div>
            <h2>
                Threaded Discussion <br>
                <span class="help prompt" style="font-weight: normal;">&nbsp;&nbsp;<br>&nbsp;&nbsp;Only the owner of a comment can edit or delete it</span>
            </h2>
            <div id=comments></div>
        </div>

        <script>

			var installDir = function(){
				 var path = (top ? top.location.pathname : (window ? window.location.pathname : ""));
				 if ( path && path != "undefined") {
	 				path = path.match(/\/[^\s\/]\//);
	 				path = path ? path.replace(/\//g,"") : "";
	 				return path;
				 }
				 return "";
			}();
            function changed() { top.HEURIST.edit.changed("discussion"); }
            function unchanged() { top.HEURIST.edit.unchanged("discussion"); }

            document.forms[0].heuristForceSubmit = function() {
                /*
                if (wootEditor.unlockedChunk) {
                wootEditor.save();
                }
                */

                for (var i in openComments) {
                    openComments[i].save();
                }
            }


            // comments stuff

            var openComments = {};

            var Comment = function(parentComment, details) {
                this.document = parentComment.document;
                this.parentComment = parentComment;
                if (parentComment) {
                    if (! parentComment.childComments) parentComment.childComments = [];
                    parentComment.childComments.push(this);
                }
                this.details = details;

                this.id = details.id;

                this.div = parentComment.div.appendChild(document.createElement("div"));
                this.div.className = "comment";
                this.innerDiv = this.div.appendChild(this.document.createElement("div"));

                if (details.deleted) {
                    this.innerDiv.className = "deleted";
                    this.innerDiv.appendChild(this.document.createTextNode("(This comment has been deleted)"));
                    this.div.style.display = "none";
                    return;
                }
                if (parentComment.details  &&  parentComment.details.deleted) {
                    parentComment.div.style.display = "";
                }

                this.innerDiv.className = "block";

                this.headerDiv = this.innerDiv.appendChild(this.document.createElement("div"));
                this.headerDiv.className = "header";
                this.author = this.headerDiv.appendChild(this.document.createElement("a"));
                this.author.className = "author";
                this.author.appendChild(this.document.createTextNode(details.user));
                if (details.added) {
                    var date = this.headerDiv.appendChild(this.document.createElement("span"));
                    date.className = "date";
                    date.appendChild(this.document.createTextNode(this.formatDate(details.added)));
                }
                if (details.modified) {
                    var modDate = this.headerDiv.appendChild(this.document.createElement("span"));
                    modDate.className = "moddate";
                    modDate.appendChild(this.document.createTextNode(" (modified " + this.formatDate(details.modified) + ")"));
                }

                var detailText = details.text || "";
                detailText = detailText.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
                detailText = detailText.replace(/(http:\/\/[\041-\176]+)/g, "<a href=\"$1\">$1</a>");
                detailText = detailText.replace(/\[(\d+)\]/g, "[<a href=\"/"+ installDir +"/records/view/viewRecord.php?recID=$1\">$1</a>]");

                this.textDiv = this.innerDiv.appendChild(this.document.createElement("div"));
                this.textDiv.className = "text";
                this.textDiv.innerHTML = detailText;

                this.footerDiv = this.innerDiv.appendChild(this.document.createElement("div"));
                this.footerDiv.className = "footer";

                this.footerDiv.appendChild(this.document.createTextNode("("));
                this.replyLink = this.footerDiv.appendChild(this.document.createElement("a"));
                this.replyLink.href = "#";
                this.replyLink.appendChild(this.document.createTextNode("Reply"));
                this.footerDiv.appendChild(this.document.createTextNode(")"));

                var thisRef = this;
                this.replyLink.onclick = function() { thisRef.reply(); return false; };

                if (details.userID == top.HEURIST.get_user_id()) {
                    this.footerDiv.appendChild(this.document.createTextNode(" ("));
                    this.editLink = this.footerDiv.appendChild(this.document.createElement("a"));
                    this.editLink.href = "#";
                    this.editLink.appendChild(this.document.createTextNode("Edit"));
                    this.footerDiv.appendChild(this.document.createTextNode(") "));

                    var thisRef = this;
                    this.editLink.onclick = function() { thisRef.edit(); return false; };

                    this.footerDiv.appendChild(this.document.createTextNode(" ("));
                    this.deleteLink = this.footerDiv.appendChild(this.document.createElement("a"));
                    this.deleteLink.href = "#";
                    this.deleteLink.appendChild(this.document.createTextNode("Delete"));
                    this.footerDiv.appendChild(this.document.createTextNode(") "));

                    this.deleteLink.onclick = function() { thisRef.remove(); return false; };
                }
            };
            Comment.prototype.edit = function() {
                var editComment = new EditableComment(this);
                this.div.replaceChild(editComment.innerDiv, this.innerDiv);
                editComment.textarea.focus();
            };
            Comment.prototype.reply = function() {
                var editComment = new EditableComment(null, this);

                // Put the editable reply immediately after the comment being replied to,
                // even though the eventual comment will be at the bottom
                if (! this.innerDiv.nextSibling) {
                    this.div.appendChild(editComment.div);
                } else {
                    this.div.insertBefore(editComment.div, this.innerDiv.nextSibling);
                }
                editComment.textarea.focus();
            };
            Comment.prototype.remove = function() {
                if (! confirm("Delete this comment?")) return;

                var fakeForm = { action: installDir + "records/comments/saveThreadedComments.php",
                    elements: [
                    { name: "cmt_ID", value: this.id },
                    { name: "delete", value: 1 }
                    ] };
                var thisRef = this;

                top.HEURIST.util.xhrFormSubmit(fakeForm, function(json) {
                    var vals = eval(json.responseText);

                    if (vals  &&  vals.error) {
                        alert("Error while deleting:\n" + vals.error);
                        return;
                    }

                    thisRef.details.deleted = true;
                    thisRef.div.removeChild(thisRef.innerDiv);

                    thisRef.innerDiv = thisRef.document.createElement("div");
                    thisRef.innerDiv.className = "deleted";
                    thisRef.innerDiv.appendChild(thisRef.document.createTextNode("(This comment has been deleted)"));

                    if (thisRef.div.firstChild)
                    thisRef.div.insertBefore(thisRef.innerDiv, thisRef.div.firstChild);
                    else
                    thisRef.div.appendChild(thisRef.innerDiv);
                });
            };
            Comment.prototype.formatDate = function(date) {
                var date = new Date(Date.parse(date.replace(/-/g, "/")));
                var now = new Date(Date.parse(top.HEURIST.edit.record.retrieved.replace(/-/g, "/")));

                var dateTime = Math.round(date.getTime() / 1000);
                var nowTime = Math.round(now.getTime() / 1000);

                /* less than two hours ago */
                if ((nowTime - dateTime) <= 119*60) {
                    var mins = Math.round((nowTime - dateTime) / 60);
                    if (mins == 0) return "less than one minute ago";
                    else if (mins == 1) return "1 minute ago";
                    return mins + " minutes ago";
                }

                /* less than a day ago */
                if ((nowTime - dateTime) <= 23*60*60) {
                    var hours = Math.round((nowTime - dateTime) / (60*60));
                    return hours + " hours ago";
                }

                /* e.g. "yesterday 6:39pm" */
                if ((nowTime - dateTime) < 48*60*60  &&  now.getDay() == date.getDay()+1) {
                    return "yesterday " + this.formatTime(date.getHours(), date.getMinutes());
                }

                /* less than a week ago -- e.g. "Tuesday 6:39pm" */
                if ((nowTime - dateTime) < 7*24*60*60) {
                    return this.dayNames[date.getDay()] + " " + this.formatTime(date.getHours(), date.getMinutes());
                }

                /* this year */
                if (now.getFullYear() == date.getFullYear()) {
                    return this.monthNames[date.getMonth()] + " " + date.getDate() + ", " + this.formatTime(date.getHours(), date.getMinutes());
                }

                /* else ... */
                return this.monthNames[date.getMonth()] + " " + date.getDate() + " " + date.getFullYear() + ", " + this.formatTime(date.getHours(), date.getMinutes());
            };
            Comment.prototype.formatTime = function(hours, minutes) {
                if (hours > 12)
                return (hours - 12) + ":" + minutes + "pm";
                else
                return hours + ":" + minutes + "am";
            };
            Comment.prototype.dayNames = [ "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ];
            Comment.prototype.monthNames = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ];

            var EditableComment = function(associatedComment, parentComment) {
                this.comment = associatedComment;

                if (associatedComment) {
                    this.document = associatedComment.document;
                    this.details = this.comment.details;
                    this.id = this.details.id;
                    this.parentComment = associatedComment.parentComment;
                    this.div = associatedComment.div;
                } else {
                    this.document = parentComment.document;
                    this.details = {};
                    this.id = 0;
                    this.parentComment = parentComment;
                    this.div = this.document.createElement("div");
                    this.div.className = "comment";
                }
                this.innerDiv = this.document.createElement("div");
                this.innerDiv.className = "editing-block";

                if (! associatedComment) {
                    this.div.appendChild(this.innerDiv);
                }

                this.textarea = this.innerDiv.appendChild(this.document.createElement("textarea"));
                this.textarea.value = this.textarea.defaultValue = this.details.text? this.details.text : "";
                //	var helpDiv = this.innerDiv.appendChild(this.document.createElement("div"));
                //		helpDiv.className = "help prompt";
                //		helpDiv.appendChild(this.document.createTextNode("Reference other records as [XXX] where XXX is the record number"));

                var thisRef = this;
                this.saveButton = this.document.createElement("input");
                this.saveButton.type = "button";
                this.saveButton.value = "Save edit";
                this.saveButton.onclick = function() { thisRef.save(); };
                this.innerDiv.appendChild(this.saveButton);

                this.cancelButton = this.document.createElement("input");
                this.cancelButton.type = "button";
                this.cancelButton.value = "Cancel edit";
                this.cancelButton.onclick = function() { thisRef.cancel(); return false; };
                this.innerDiv.appendChild(this.cancelButton);

                this.deleteButton = this.document.createElement("input");
                this.deleteButton.type = "button";
                this.deleteButton.value = "Delete comment";
                this.innerDiv.appendChild(this.deleteButton);

                do {
                    this.nonce = Math.floor(Math.random() * 1000000);
                } while (openComments[this.nonce]);
                openComments[this.nonce] = this;
            };
            EditableComment.prototype.save = function() {
                if (this.textarea.value == "") {
                    // Don't bother saving an empty input
                    this.cancel();
                    return;
                }

                var fakeForm = { action: installDir + "records/comments/saveThreadedComments.php",
                    elements: [
                    { name: "cmt_ID", value: this.id },
                    { name: "recID", value: parent.HEURIST.edit.record.bibID },
                    { name: "owner",  value: this.parentComment.id },
                    { name: "text",   value: this.textarea.value }
                    ] };
                var thisRef = this;

                top.HEURIST.util.xhrFormSubmit(fakeForm, function(json) {
                    var vals = eval(json.responseText);
                    if (! vals) return;

                    if (vals.error) {
                        alert("Error while saving:\n" + vals.error);
                    } else if (vals.comment) {
                        newComment = new Comment(thisRef.parentComment, vals.comment);
                        if (thisRef.comment) {
                            // replace this new comment where the old one was
                            thisRef.div.parentNode.replaceChild(newComment.div, thisRef.div);
                        } else {
                            thisRef.div.parentNode.removeChild(thisRef.div);
                        }

                        newComment.replyLink.focus();
                        newComment.author.focus();

                        delete openComments[thisRef.nonce];
                    }
                });
            }
            EditableComment.prototype.cancel = function() {
                if (this.comment) {
                    /* replace this editable comment with the plain comment that it replaced */
                    this.div.replaceChild(this.comment.innerDiv, this.innerDiv);
                } else {
                    this.div.parentNode.removeChild(this.div);
                }

                delete openComments[thisRef.nonce];
            };


            function printAllComments() {
                var commentDetails = parent.HEURIST.edit.record.comments;
                var comments = {};

                var commentsDiv = document.getElementById("comments");
                var topLevelComment = { document: document, id: 0, div: commentsDiv };
                comments[0] = topLevelComment;

                var commentLink = document.createElement("a");
                commentLink.href = "#";
                commentLink.id = "comment-link";
                commentLink.appendChild(document.createTextNode("New comment"));
                commentLink.onclick = function() {
                    var editComment = new EditableComment(null, topLevelComment);
                    commentLink.parentNode.insertBefore(editComment.div, commentLink.nextSibling);
                    editComment.textarea.focus();
                    return false;
                };
                commentsDiv.appendChild(commentLink);

                for (var cmtID in commentDetails) {
                    var commentDetail = commentDetails[cmtID];

                    if (comments[commentDetail.owner]) {
                        comments[cmtID] = new Comment(comments[commentDetail.owner], commentDetail);
                    }
                    else {	/* ownerless comment is just a stub for grouping -- deprecated */
                        comments[cmtID] = topLevelComment;
                    }
                }
            }

            printAllComments();

        </script>




    </body>
</html>
